<?php

class LogoAction extends sfActions
{
    public function execute($request)
    {
        $ad_session = new AdSession($this->getUser()->getUid());
        $ad = $ad_session->getSession();

        if ($request->getParameter('for') === 'company')
            $this->logo_data = $ad['company_logo_data'];
        else
            $this->logo_data = $ad['creatives'][$request->getParameter('for')]['image'];

        $this->has_logo = (bool) $this->logo_data;
        $this->error = null;

        if ($request->getMethod() === sfRequest::POST) {
            $this->setLayout(false);

            $files = $request->getFiles();

            if (!array_key_exists('file', $files)) {
                $this->error = 'No file submitted.';
            } else if ($files['file']['error']) {
                if (in_array($files['file']['error'], array(
                            UPLOAD_ERR_INI_SIZE,
                            UPLOAD_ERR_FORM_SIZE,
                            )))
                    $this->error = 'The file size is too large.';
                else
                    $this->error = 'An upload error occured.';
            } else {
                $image_data = file_get_contents($files['file']['tmp_name']);
                if ($image_data === false) {
                    $this->error = 'An upload error occured.';
                } else {
                    $image_data = LogoManager::resizeLogo($image_data);
                    if (!$image_data) {
                        $this->error = 'Unknown image format.';
                    } else {
                        if ($request->getParameter('for') === 'company')
                            $ad['company_logo_data'] = base64_encode($image_data);
                        else
                            $ad['creatives'][$request->getParameter('for')]['image'] = base64_encode($image_data);

                        $ad_session->saveSession($ad);
                    }
                }
                $this->setLayout(false);
                $this->has_logo = true;
            }
            return sfView::SUCCESS;
        } else {
            // Return an upload form for the dialog iframe
            if ($request->getParameter('mode') === 'form') {
                $this->setLayout(false);
                return sfView::SUCCESS;
            }

            $logo_data = $request->getParameter('for') === 'company' ? $ad['company_logo_data'] : $ad['creatives'][$request->getParameter('for')]['image'];
            echo LogoManager::getImage($logo_data);

            return sfView::NONE;
        }
    }
}

?>
